<template>
  <el-dialog v-model="drawer" width="730px" :append-to-body="true" :title="title" @close="close" :close-on-click-modal="true" custom-class="createDetail">
    <el-form size="small" :model="form" :rules="rules" label-width="90px" ref="ruleRefForm">
        <el-row justify="space-between">
            <el-form-item label="订单类别:" prop="classOther" >
                <el-radio-group v-model="form.classOther" class="ml-4" @change="selectClasses">
                    <el-radio :label="0">个人采购单</el-radio>
                    <el-radio :label="1">企业采购单</el-radio>
                </el-radio-group>
            </el-form-item>
        </el-row>
        <el-row justify="space-between">
            <el-form-item label="下单日期" prop="createTime">
                <el-date-picker style="width: 252px;" v-model="form.createTime" type="datetime" placeholder="请选择" size="small" value-format="YYYY-MM-DD HH:mm:ss" />
            </el-form-item>
            <el-form-item label="订单来源" prop="sourceType">
                <el-select v-model="form.sourceType" placeholder="请选择" size="small" style="width: 252px;">
                    <el-option
                        v-for="item in sourceList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                </el-select>
            </el-form-item>
        </el-row>
        <el-row justify="space-between">
            <el-form-item label="客户名称" prop="customerId">
                <el-select v-model="form.customerId" placeholder="请选择" size="small" style="width: 252px;" filterable remote :remote-method="getCustomer" @change="customerChoose">
                    <el-option
                        v-for="item in customerList"
                        :key="item.id"
                        :label="item.nickname"
                        :value="item.id"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="订单归属人" prop="belongerId">
                <my-input v-if="!isEdit" v-model="form.belongerName" width="180" @circle="circleCustomerManageEvent" placeholder="请选择客户经理" @click.stop.prevent="dialogCustomerManage = true"/>                
                <el-tag v-else class="ml-2" type="success">{{ form.belongerName }}</el-tag>
                <!-- <el-select v-model="form.belongerId" placeholder="请选择" size="small" style="width: 252px;">
                    <el-option
                        v-for="item in manageList"
                        :key="item.id"
                        :label="item.label"
                        :value="item.value"
                    />
                </el-select> -->
            </el-form-item>
        </el-row>
        <el-row justify="space-between">
            <el-form-item label="联系人" prop="receiverName">
                <el-input placeholder="请输入" v-model="form.receiverName"></el-input>
                <!-- <el-select v-model="form.customerId" clearable placeholder="请选择联系人" @change="selectCustomer">
                    <el-option
                        v-for="item in contactsList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                        />
                </el-select> -->
            </el-form-item>
            <el-form-item label="联系电话" prop="receiverPhone">
                <el-input placeholder="请输入" v-model="form.receiverPhone" maxlength="11"></el-input>
            </el-form-item>
        </el-row>
        <el-form-item label="选择区域" prop="area">
            <el-cascader
                ref="areaTree"
                v-model="area"
                :options="citys"
                :props="props"
                @change="handleChange"
                style="width:593px"
            />
        </el-form-item>
        <el-form-item label="收货地址" prop="receiverDetailAddress">
            <el-input placeholder="请输入" v-model="form.receiverDetailAddress"></el-input>
        </el-form-item>
        <el-row>
            <el-button size="small" type="primary" plain @click="addProduct"><el-icon><ele-CirclePlus /></el-icon>添加产品</el-button>
        </el-row>
        <el-table size="small" :data="form.orderItemList" border style="margin-top:10px;margin-bottom:18px;">
            <el-table-column label="产品编号" prop="spuId"></el-table-column>
            <el-table-column label="产品名称" prop="spuName"></el-table-column>
            <el-table-column label="详情/规格" prop="skuName">
                <template #default="scope">
                    {{scope.row.skuName || '无规格'}}
                </template>
            </el-table-column>
            <el-table-column label="数量" prop="skuQuantity" align="center" width="100px">
                <template #default="scope">
                    <el-input-number style="width:80px" v-model="scope.row.skuQuantity" size="small" :step="1" :min="0" :max="scope.row.stock" />
                </template>
            </el-table-column>
            <el-table-column label="单价" prop="skuPrice" align="center" width="70px"></el-table-column>
            <el-table-column label="总价" prop="total" align="center" width="70px">
                <template #default="scope">{{getRowTotal(scope.row)}}</template>
            </el-table-column>
            <el-table-column label="折扣" prop="discount" align="center" width="100px">
                <template #default="scope">
                    <el-input-number style="width:80px" v-model="scope.row.discount" size="small" :step="0.01" :min="0.01" :max="1" />
                </template>
            </el-table-column>
            <el-table-column label="折后价" prop="afterDiscountTotal" align="center" width="60px">
                <template #default="scope">
                    <span v-if="scope.row.discount != null && scope.row.discount != 0">{{getRowTotal(scope.row) * scope.row.discount}}</span>
                    <span>{{getRowTotal(scope.row)}}</span>
                </template>
            </el-table-column>
            <el-table-column label="备注" prop="remark" width="120px">
                <template #default="scope">
                    <el-input v-model="scope.row.remark" :rows="1" type="textarea" placeholder="请输入" />
                </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="80px" align="center">
                <template #default="scope">
                    <el-button @click="delProduct(scope.$index)" type="danger" link>删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-form-item v-if="form.rootIn != 6" label="合计"><span style="font-weight:bold;font-size:14px;" class="red">￥{{getTotal}}</span></el-form-item>
        <el-form-item v-else label="合计">
            <el-input-number  v-model="adjustMoney" :precision="2" :step="1" ></el-input-number>
        </el-form-item>
        <el-form-item label="大写"><span style="font-weight:bold;font-size:14px;">{{getCaps}}</span></el-form-item>
        <!-- <el-row>
            <el-col :span="24">
                <el-row>
                    
                    <el-form-item label="是否含税">
                        <el-radio-group v-model="form.isTax">
                            <el-radio :label="1" size="small">是</el-radio>
                            <el-radio :label="2" size="small">否</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-row>
            </el-col>
        </el-row> -->
        <el-form-item label="是否开票">
            <el-radio-group v-model="form.billType">
                <el-radio :label="0" size="small">否</el-radio>
                <el-radio :label="1" size="small">电子发票</el-radio>
                <el-radio :label="2" size="small">纸质发票</el-radio>
            </el-radio-group>
        </el-form-item>
        <el-row>
            <el-form-item label="结款方式">
                <el-row>
                    <el-select v-model="form.settlement" placeholder="请选择" size="small">
                        <el-option
                            v-for="item in settlementList"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                    <el-tooltip
                        effect="dark"
                        content="付款规则设置"
                        placement="right"
                    >
                        <el-icon @click="handleRuleSetting" style="position:absolute;right: -18px;top: 5px;font-size: 14px;cursor:pointer;"><ele-Setting /></el-icon>
                    </el-tooltip>
                </el-row>
            </el-form-item>
            <el-form-item label="付款渠道" prop="payType">
                <el-select v-model="form.payType" placeholder="请选择" size="small">
                    <el-option
                        v-for="item in payTypeList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    />
                </el-select>
            </el-form-item>
            <el-form-item v-if="entrance == 'ORDER'" label="订单阶段">
                <el-select v-model="form.status" placeholder="请选择" size="small">
                    <el-option
                        v-for="item in orderStageList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    />
                </el-select>
            </el-form-item>
        </el-row>
        <el-row>
            <el-col :span="16">
                <el-row v-if="entrance == 'ORDER'">
                    <el-form-item  label="付款状态">
                        <el-select v-model="form.payStatus" placeholder="请选择" size="small">
                            <el-option
                                v-for="item in payStatusList"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="发货状态">
                        <el-select v-model="form.logisticStatus" placeholder="请选择" size="small">
                            <el-option
                                v-for="item in logisticStatusList"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                            />
                        </el-select>
                    </el-form-item>
                </el-row>
            </el-col>
        </el-row>
        <!-- <el-form-item label="包装要求">
            <el-input v-model="form.packingAskFor" placeholder="请输入"></el-input>
        </el-form-item> -->
        <el-row>
            <el-form-item label="发货方式">
                <el-select v-model="form.deliveryType" placeholder="请选择" size="small">
                    <el-option
                        v-for="item in logisticTypeList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="物流公司">
                <el-select v-model="form.deliveryCompany" placeholder="请选择" size="small">
                    <el-option
                        v-for="item in logisticCompanyList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="要求交货日期">
                <el-date-picker v-model="form.requestDeliveryDate" type="date" placeholder="请选择" size="small" value-format="YYYY-MM-DD" style="width:138px" />
            </el-form-item>
        </el-row>
        <el-form-item label="备注" prop="note">
            <el-input type="textarea" :rows="2" v-model="form.note" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="上传合同附件" label-width="90px">
            <el-upload drag :action="action" :headers="headers" :multiple="false" :limit="1" class="upload-drag" :auto-upload="true" :on-success="handleFileSuccess">
                <el-icon size="50px"><ele-UploadFilled /></el-icon>
                <div class="el-upload__text">
                    拖拽文件到这里或 <em>点击上传</em>
                </div>
            </el-upload>
        </el-form-item>
    </el-form>
    <template #footer>
        <el-row justify="center">
            <el-button size="small" type="warning" @click="submitForm(ruleRefForm, 'draft')" v-if="!isEdit">保存为草稿</el-button>
            <el-button size="small" type="primary" @click="submitForm(ruleRefForm)" v-if="!isEdit">{{ entrance == 'SIGNATURE'?'保存到审批和签署单列表':'保存到列表' }}</el-button>
            <el-button size="small" type="primary" @click="submitForm(ruleRefForm, 'saveAndSend')" v-if="!isEdit && form.sourceType == 3 && form.rootIn != 6">提交并发送</el-button>
            <el-button size="small" type="primary" @click="submitForm(ruleRefForm, 'sendPurchase')" v-if="isEdit && myIsMatching">保存到我的采购单</el-button>
            <el-button size="small" type="default" @click="cancelForm(ruleRefForm)">取消</el-button>
        </el-row>
    </template>
    <product-list v-model:dialogDrawer="dialogProduct" @onSubmit="submitProduct" v-model:defaultChoose="form.orderItemList"></product-list>
    <organize-tree-select v-model:dialogDrawer="dialogOrganize" @onSubmit="getOrganize"></organize-tree-select>
    <money-list v-model:dialogDrawer="dialogMoney"></money-list>
    <!-- 选择客户经理 -->
    <select-staff v-model:dialogPop="dialogCustomerManage" @customer-type="selectCustomerManageEvent"></select-staff>
    <!-- 选择购买客户的企业 -->
    <select-shop-list v-model:dialogPop="selectShopStatus" v-model:list="shopList" @sel-enterprise="selEnterprise"></select-shop-list>

  </el-dialog>
</template>

<script>
import { computed, reactive, toRefs, ref, watch, getCurrentInstance, nextTick } from 'vue'
import { verifyPhone, verifyNumberCnUppercase } from '/@/utils/toolsValidate'
import ProductList from './ProductList.vue'
import SelectStaff from "../../crm/components/SelectStaff.vue"
import SelectShopList from './SelectShopList.vue'
import MyInput from "../../crm/components/MyInput.vue";
import MoneyList from './MoneyList.vue'
import { ElMessage } from 'element-plus'
import { formatDate } from '/@/utils/formatTime'
import { city } from '/@/utils/city'

import { useOrderApi } from '/@/api/order/index'
import { umsMemberApi } from '/@/api/ums/member/index';
import { storeToRefs } from 'pinia';
import { orderModelStatus } from '/@/stores/order'
import { useUserInfo } from '/@/stores/userInfo'
import { Session } from '/@/utils/storage'
import api from '/@/api/commonApi'


export default {
    name: 'CreateOrder',
    props: {
        dialogDrawer: {
            type: Boolean,
            default: false
        },
        title: {
            type: String,
            default: '新建订单'
        },
        isEdit: {
            type: Boolean,
            default: false
        },
        defaultForm: {
            type: Object,
            default: () => {
                return {}
            }
        },
        entrance: {
            type: String,
            default: 'ORDER'
        }
    },
    components: { ProductList, MoneyList, SelectStaff, MyInput, SelectShopList },
    emits: ['onSubmit', 'update:dialogDrawer'],
    setup(props, context) {
        const { dialogDrawer, defaultForm, isEdit, entrance, isValid } = toRefs(props)
        const { proxy } = getCurrentInstance()
        // 用户信息
        const storeUserInfo = useUserInfo() // 订单各类状态数据
        const { userInfos } = storeToRefs(storeUserInfo)
        const orderApi = useOrderApi()
        const memberApi = umsMemberApi()
        const storeOrder = orderModelStatus() // 订单各类状态数据
        const drawer = computed({
            get: () => {
                // 生效订单
                if (entrance.value == 'ORDER') {
                    state.form.rootIn = 0
                    state.form.isValid = 1
                }
                // 报价单转订单
                else if (entrance.value == 'QUOTE_ORDER') {
                    state.form = defaultForm.value
                    state.form.rootIn = 4
                    state.form.isValid = 0
                }
                // 签署单
                else if(entrance.value == 'SIGNATURE') {
                    state.form.rootIn = 5
                    state.form.isValid = 0
                }
                // 调整单
                else if (entrance.value == 'ADJUST') {
                    state.form.rootIn = 6
                    state.form.isValid = 1
                }
                return dialogDrawer.value
            },
            set: val => {
                context.emit('update:dialogDrawer', val)
            }
        })
        const onVerifyPhone = (rule, val, callback) => {
            if(verifyPhone(val)) {
                return callback()
            }else {
                callback(new Error('手机号格式不正确'))
            }
        }
        const ruleRefForm = ref()
        const state = reactive({
            form: {
                classOther: 0,
                createTime: '',
                memberUsername: '',
                memberId: null,
                memberType: null,
                customerId: '',
                customerName: '',
                customerSourceId: null, // 客户来源id
                customerSource: '', // 客户来源
                forCustomerId: null,
                forCustomerName: '',
                forEnterpriseId: null,
                forEnterpriseName: '',
                receiverName: '',
                receiverPhone: '',
                receiverProvince: '',
                receiverCity: '',
                receiverRegion: '',
                receiverDetailAddress: '',
                orderItemList: [],
                totalAmount: '',
                payAmount: '',
                settlement: '',
                // settlementDesc: '',
                payType: '',
                belongerId: '',
                belongerName: '',
                payStatus: '',
                status: 0,
                logisticStatus: '',
                deliveryCompany: '',
                sourceType: 3,
                billType: 0,
                requestDeliveryDate: '',
                contractFileUrl: '',
                note: '',
                deliveryType: '',
                saveAndSend: false, // 是否直发
            },
            rules: {
                customerId: [{ required: true, message: '请选择客户名称', trigger: 'blur' }],
                receiverName: [{ required: true, message: '请输入收货人', trigger: 'blur' }],
                receiverPhone: [{ required: true, message: '请输入手机号', trigger: 'blur' }, { trigger: 'blur', validator: onVerifyPhone }],
                receiverDetailAddress: [{ required: true, message: '请输入收货地址', trigger: 'blur' }],
                belongerId: [{ required: true, message: '请选择订单归属人', trigger: 'blur' }],
                createTime: [{ required: true, message: '请选择下单日期', trigger: 'blur' }]
            },
            settlementList: [{
                label: '全款结付',
                value: 0
            },{
                label: '年付',
                value: 1
            },
            {
                label: '月付',
                value: 2
            },
            {
                label: '到货后付',
                value: 3
            },
            {
                label: '自定义',
                value: 4
            },
            {
                label: '预付充值',
                value: 5
            }],
            payTypeList: storeToRefs(storeOrder).payType,
            customerList: [],
            manageList: [{
                label: '张三',
                value: 1
            }],
            orderStageList: storeToRefs(storeOrder).status,
            payStatusList: storeToRefs(storeOrder).payStatus,
            logisticStatusList: storeToRefs(storeOrder).deliveryStatus,
            logisticTypeList: storeToRefs(storeOrder).deliveryType,
            logisticCompanyList: [{
                label: '顺丰',
                value: 1
            }],
            sourceList: [
                {
                    label: '17合约',
                    value: 3
                }
            ],
            action: '/api/file/filaAttach/upload',
            headers: {
                '17work': Session.get('token')
            },
            citys: city,
            area: [],
            props: {
                expandTrigger: 'hover',
                value: 'code'
            },
            drafts: {}, // 草稿箱
            dialogProduct: false,
            dialogOrganize: false,
            dialogMoney: false,
            dialogCustomerManage: false,// 控制选择客户经理
            userId: userInfos.value.id,
            myIsMatching: false, // 当前用户是否可编辑
            shopList: [], // 企业
            selectShopStatus: false, // 选择客户企业
            contactsList: [], // 客户联系人集合
            adjustMoney: 0, // 调整金额
        })
        watch(() => dialogDrawer.value,
            val => {
                if(val){
                    state.form.createTime = formatDate(new Date, 'YYYY-mm-dd HH:MM:SS')
                    if(isEdit.value){
                        state.form = defaultForm.value
                        isOrMyOrder(state.form.customerId)
                        nextTick(() => {
                            getArea()
                        })
                    }else{
                        orderApi.getDraftDetail({
                            userId: state.userId,
                            type: 0
                        }).then(res => {
                            console.log(res)
                            if(res.data && res.data.contents) {
                                state.drafts = res.data
                                state.form = JSON.parse(res.data.contents)
                                nextTick(() => {
                                    getArea()
                                })
                            }
                        })
                    }
                    getCustomer()
                }
            }
        )
        const getTotal = computed(() => {
            const list = state.form.orderItemList
            let total = 0
            list.forEach(e => {
                total += e.skuPrice * (e.skuQuantity || 0) * (e.discount || 1)
            })
            return total
        })
        // 获取大写
        const getCaps = computed(() => {
            const list = state.form.orderItemList
            let total = 0
            list.forEach(e => {
                total += e.skuPrice * (e.skuQuantity || 0) * (e.discount || 1)
            })
            return verifyNumberCnUppercase(total)
        })
        // 获取单个总价
        const getRowTotal = computed(() => {
            return row => {
                let total = 0
                total += row.skuPrice * (row.skuQuantity || 0)
                return total
            }
        })
        const close = () => {
            reset()
            context.emit('update:dialogDrawer', false)
        }
        const delProduct = (index) => {
            state.form.orderItemList.splice(index, 1)
        }
        // 保存
        const submitForm = (formEl, type) => {
            if (!formEl) return
            formEl.validate((valid) => {
                if (valid) {
                    if(type == 'draft') {
                        // 草稿
                        orderApi.createDraft({
                            userId: state.userId,
                            type: 0,
                            contents: JSON.stringify(state.form)
                        }).then(() => {
                            ElMessage.success('保存草稿成功')
                            formEl.resetFields()
                            context.emit('onSubmit')
                            context.emit('update:dialogDrawer', false)
                        })
                    }
                    // 直发
                    else if(type == 'sendPurchase'){
                        api.orderSendPurchase(state.form).then(res => {
                            ElMessage.success('直发成功！')
                            formEl.resetFields()
                            delDraft()
                            context.emit('onSubmit')
                            context.emit('update:dialogDrawer', false)
                        })
                    }
                    else{
                        if(state.form.orderItemList.length < 1 && state.form.rootIn != 6) {
                            ElMessage.error('请至少添加一个产品')
                            return 
                        }
                        if(isEdit.value){
                            // 编辑

                        }else{
                            if(state.form.rootIn == 6) {
                                state.form.totalAmount = state.adjustMoney
                                state.form.payAmount = state.adjustMoney
                                state.form.status = 3
                                if(state.form.orderItemList.length > 0) {
                                    state.form.status = 1
                                }
                            }else {
                                state.form.totalAmount = getTotal
                                state.form.payAmount = getTotal
                            }
                            state.form.createTime = state.form.createTime
                            if(type == 'saveAndSend'){
                                state.form.saveAndSend = true
                                state.form.isApprove = 1
                                state.form.approveState = 2
                            }
                            orderApi.createOrder(state.form).then(res => {
                                console.log(res)
                                formEl.resetFields()
                                delDraft()
                                context.emit('onSubmit')
                                context.emit('update:dialogDrawer', false)
                            })
                        }
                    }
                }
            })
        }
        // 取消
        const cancelForm = formEl => {
            if (!formEl) return
            formEl.resetFields()
            reset()
            context.emit('update:dialogDrawer', false)
        }
        // 获取选择的产品
        const submitProduct = val => {
            let list = []
            val.forEach(e => {
                let skuData = {}
                for(let i = 0; i < e.skuInfos.length; i++){
                    if(e.chooseSpec[0] == e.skuInfos[i].skuId){
                        skuData = e.skuInfos[i]
                    }
                }
                list.push({
                    spuId: e.id,
                    spuName: e.spuName,
                    spuPic: e.image,
                    spuBrand: null,
                    categoryId: skuData.catalogId,
                    skuId: skuData.skuId,
                    skuName: skuData.skuName,
                    skuPic: e.skuPic,
                    skuPrice: skuData.price,
                    skuQuantity: e.skuQuantity,
                    skuAttrsVals: null,
                    promotionAmount: null,
                    realAmount: null,
                    couponAmount: null,
                    shopId: e.merchantsId,
                    saleMoney: skuData.saleMoney                  
                })
            })
            state.form.orderItemList = state.form.orderItemList.concat(list)
            console.log(list);
        }
        // 添加产品
        const addProduct = () => {
            state.dialogProduct = true
        }
        // 获取客户
        const getCustomer = (e) => {
            api.customerList({type: state.form.classOther == 0?1:0}).then(res => {
                state.customerList = res.data
            })
        }
        // 选择客户
        const customerChoose = e => {
            const result = state.customerList.find(item => {
                return item.id == e
            })
            if(result) {
                state.form.memberUsername = result.nickname
                state.form.customerId = result.id
                state.form.customerName = result.intactName
                // 客户来源
                if(result.sourceChannel){
                    api.customerSource(result.sourceChannel).then(res => {
                        if (res.data) {
                            state.form.customerSourceId = result.sourceChannel || null
                            state.form.customerSource = res.data.name
                            // 17购订单
                            if(res.data.pname == '17购'){
                                state.form.placeType = 1
                            }
                        }
                    })
                }
                // 选择个人
                if (state.form.classOther == 0) {
                    api.getCustomerContacts({memberId: result.id}).then(res => {
                        state.contactsList = res.data
                        if(res.data.length > 0){
                            state.form.receiverName = res.data[0].name
                            state.form.receiverPhone = res.data[0].phone
                            state.form.forCustomerId = res.data[0].id
                            state.form.forCustomerName = res.data[0].name
                        }else{
                            state.form.receiverName = ''
                            state.form.receiverPhone = ''
                            state.form.forCustomerId = null
                            state.form.forCustomerName = null
                        }
                    })
                }
                // 选择企业
                else {
                    api.getCustomerContacts({memberId: result.id}).then(res => {
                        if(res.data) {
                            state.contactsList = res.data
                            state.form.receiverName = res.data[0].name
                            state.form.receiverPhone = res.data[0].phone
                        }
                    })
                    matchingEmterprose(result.intactName, result.branchName)
                }
            }
        }
        // 匹配企业
        const matchingEmterprose = (intactName, branchName) => {
            api.enterpriseFieldMatching({
                intactName: intactName,
                branchName: branchName || ''
            }).then(res => {
                if(res.data.length > 0) {
                    state.form.forEnterpriseId = res.data.id
                    state.form.forEnterpriseName = res.data.name
                }else{
                    ElMessage.warning("未匹配到相应企业，请联系此客户")
                    state.form.forEnterpriseId = ''
                    state.form.forEnterpriseName = ''
                    state.form.classOther = 0
                }
            })
        }
        // 选择客户联系人
        const selectCustomer = (val) => {
            console.log(val);
        }
        // 客户经理 -清除选择
        const circleCustomerManageEvent = () => {
            state.form.belongerId = ''
            state.form.belongerName = ''
        }
        // 客户经理 - 添加选择
        const selectCustomerManageEvent = obj => {
            const {id, nickname} = obj
            state.form.belongerId = id
            state.form.belongerName = nickname
        }
        // 文件上传
        const handleFileSuccess = e => {
            state.form.contractFileUrl = e.data.src
        }
        // 获取指派的待办人
        const getOrganize = val => {
            console.log(val)
        }
        const handleChange = () => {
            const area = proxy.$refs['areaTree'].getCheckedNodes()[0].pathLabels
            state.form.receiverProvince = area[0]
            state.form.receiverCity = area[1]
            state.form.receiverRegion = area[2]
        }
        const getArea = () => { // 省市区数据筛选
            const provinceList = state.citys.find(item => {
                return item.label == state.form.receiverProvince
            })
            let area = []
            if(provinceList){
                area[0] = provinceList.code
                const citysList = provinceList.children.find(item => {
                    return item.label == state.form.receiverCity
                })
                if(citysList){
                    area[1] = citysList.code
                    const areaList = citysList.children.find(item => {
                        return item.label == state.form.receiverRegion
                    })
                    if(areaList){
                        area[2] = areaList.code
                    }
                }
            }
            state.area = area
        }
        const handleRuleSetting = () => {
            state.dialogMoney = true
        }
        // 删除草稿箱
        const delDraft = () => {
            if(state.drafts.id){
                orderApi.delDraft(state.drafts.id)
            }
        }
        // 我是否可操作
        const isOrMyOrder = (id) => {
            api.isMyByMatching({ customerId: id }).then(res => {
                state.myIsMatching = res.data
            })
        }
        // 选择个人或企业
        const selectClasses = e => {
            state.form.forEnterpriseId = ''
            state.form.forEnterpriseName = ''
            if(e == 0) {
                state.form.receiverName = ''
                state.form.receiverPhone = ''
                state.form.customerId = ''
                state.form.customerName = ''
            }
            getCustomer()
        }
        // 选择企业
        const selEnterprise = val => {
            console.log(val);
            state.form.forEnterpriseId = val.id
            state.form.forEnterpriseName = val.name
        }
        // 重置
        const reset = () => {
            state.form = {
                classOther: 0,
                createTime: '',
                memberUsername: '',
                memberId: null,
                memberType: null,
                customerId: null,
                customerName: '',
                customerSourceId: null, // 客户来源id
                customerSource: '', // 客户来源
                forCustomerId: null,
                forCustomerName: '',
                forEnterpriseId: null,
                forEnterpriseName: '',
                receiverName: '',
                receiverPhone: '',
                receiverProvince: '',
                receiverCity: '',
                receiverRegion: '',
                receiverDetailAddress: '',
                orderItemList: [],
                totalAmount: '',
                payAmount: '',
                settlement: '',
                // settlementDesc: '',
                payType: '',
                belongerId: '',
                belongerName: '',
                payStatus: '',
                status: 0,
                logisticStatus: '',
                deliveryCompany: '',
                sourceType: 3,
                billType: 0,
                requestDeliveryDate: '',
                contractFileUrl: '',
                note: '',
                deliveryType: '',
                saveAndSend: false, // 直发
            }
        }

        return {
            ...toRefs(state),
            drawer,
            close,
            reset,
            delProduct,
            getTotal,
            getCaps,
            delDraft,
            isOrMyOrder,
            ruleRefForm,
            submitForm,
            cancelForm,
            submitProduct,
            getRowTotal,
            addProduct,
            getCustomer,
            customerChoose,
            handleFileSuccess,
            getOrganize,
            handleChange,
            selectClasses,
            selEnterprise,
            selectCustomer,
            circleCustomerManageEvent,
            selectCustomerManageEvent,
            handleRuleSetting,
            matchingEmterprose
        }
    }
}
</script>

<style lang="scss">
.createDetail{
    .el-form-item{
        align-items: start;
        flex: 1;
    }
    .el-dialog__footer{
        border-top: 1px solid var(--el-border-color-extra-light);
    }
    .red {
        color: var(--el-color-danger);
    }
    .upload-drag{
        width: 100%;
    }
    .el-row.is-justify-space-between{
        flex-wrap: nowrap;
    }
}
</style>